package com.init.bootframe.system.controller;

import com.init.bootframe.system.service.IUploadFileService;
import com.init.bootframe.system.vo.Ueditor;
import com.init.bootframe.util.UEditorPublicMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * 百度富文本上传功能
 */
@Controller
@RequestMapping("/ueditor")
public class UEditorController {

    @Value("${server.servlet.context-path}")
    private String projectName;  // 项目名称

    @Value("${custom.http.addr}")
    private String httpAddr;  // 项目名称

    @Value("${custom.file.upload}")
    private String uploadPath; // 文件储存盘符地址


    private Logger logger = LoggerFactory.getLogger(UEditorController.class);

    @Autowired
    private IUploadFileService uploadFileService; // 文件上传

    /**
     * 获取文件配置
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/config")
    public String config(HttpServletRequest request) {
        return UEditorPublicMsg.UEDITOR_CONFIG;
    }

    /**
     * 文件上传
     * @param upfile
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/imgUpload")
    public Ueditor imgUpload(MultipartFile upfile){
        Ueditor ueditor = new Ueditor();
        if (!upfile.isEmpty()){
            // 设置文件保存路径
            String filePath = "";
            String fileName = upfile.getOriginalFilename();
            String[] fileNames = fileName.split("\\.");
            String suffix = fileNames[1].toLowerCase(); //文件后缀(小写)

            // 判断文件是图片还是视频
            if (suffix.equals("png") || suffix.equals("jpg") || suffix.equals("jpeg") || suffix.equals("gif") || suffix.equals("bmp")){
                filePath = "umeditorImage";
            }else if(suffix.equals("mp4") || suffix.equals("mp3") || suffix.equals("avi") || suffix.equals("swf")) {
                filePath = "umeditorVideo";
            }else {
                filePath = "umeditorFile";
            }
            try {
                // 保存新文件名字
                String newName = String.valueOf(System.currentTimeMillis()) + "." + suffix;
                filePath = File.separator + projectName + File.separator + filePath + File.separator;
                // 数据库路径
                String newPath = File.separator + "upload" + filePath + newName;
                logger.debug("数据库保存路径"+ newPath);
                // 磁盘路径
                String newFilePath = uploadPath + filePath;
                // 如果目录不存在则创建
                File uploadDir = new File(newFilePath);
                // 文件存放到file目录下,如果该文件夹不存在,则创建
                if (!uploadDir.exists() && !uploadDir.isDirectory()) {
                    boolean mkdirs = uploadDir.mkdirs();
                    if (!mkdirs) {
                        logger.error("创建目录失败！！！");
                    }
                }
                upfile.transferTo(new File(newFilePath + newName));
                ueditor.setState("SUCCESS");
                ueditor.setUrl(httpAddr + newPath);
                ueditor.setTitle(fileName);
                ueditor.setOriginal(fileName);
            }catch (Exception e){
                ueditor.setState("error");
                e.printStackTrace();
                logger.error("富文本上传文件出现异常");
                throw new RuntimeException("富文本上传文件出现异常");
            }
        }
        return ueditor;
    }

}
